/**
 * 
 */
package es.titoapps.spanishhandball.preferences;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import es.titoapps.spanishhandball.R;
import es.titoapps.spanishhandball.iu.CustomListFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;

/**
 * @author NUEVOSCANALES
 *
 */
public class MainOptionsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{

	private static Map<String,Boolean> preferences;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferences=new HashMap<String,Boolean>();
        addPreferencesFromResource(R.xml.options);
    }

	@Override
	protected void onResume() {
	    super.onResume();
	    // Set up a listener whenever a key changes
	    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		//int valorActual=sharedPreferences.getInt(key,100);

		if(preferences.containsKey(key) && !key.equalsIgnoreCase(this.getString(R.string.configMaxNewsKey))
										&& !key.equalsIgnoreCase(this.getString(R.string.configNumberOfNewsToShowKey)))
			preferences.remove(key);
		else
			preferences.put(key,true);
	}

	public void onBackPressed(){
		
		// Unregister the listener whenever a key changes
	    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);

	    Intent data = new Intent();
	    
	    for (Entry<String, Boolean> entry: preferences.entrySet()) 
			data.putExtra(entry.getKey(), entry.getValue());
		
	    if(preferences.size()>0)
	    	setResult(CustomListFragment.PREFERENCES_CHANGED, data);
	    else
	    	setResult(CustomListFragment.PREFERENCES_NOT_CHANGED, null);

	    finish();

	}
}
